package com.spica.spicaschool.ui.explore

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.drakeet.multitype.ItemViewDelegate
import com.spica.spicaschool.R
import com.spica.spicaschool.bean.news.News
import com.spica.spicaschool.databinding.ItemNewsBinding
import com.spica.spicaschool.utils.toUid

/**
 * 新闻的适配器
 */
class NewsDelegate constructor(val activity: Activity) :
    ItemViewDelegate<News, NewsDelegate.ViewHolder>() {

    private val navController =
        Navigation.findNavController(activity, R.id.fragment_container_view)


    class ViewHolder(val viewBinding: ItemNewsBinding) : RecyclerView.ViewHolder(viewBinding.root)

    override fun onBindViewHolder(holder: ViewHolder, item: News) {

        with(holder.viewBinding) {
            tvTitle.text = item.title
            tvDesc.text = item.description
            ivHeadPic.load(item.headpic)
            tvSource.text = item.source
            root.setOnClickListener {
                val bundle = bundleOf(Pair("id", item.id))
                navController.navigate(R.id.action_home_to_news_detail, bundle)
            }
        }

    }

    override fun getItemId(item: News): Long {
        return item.id.toUid().toLong()
    }

    override fun onCreateViewHolder(context: Context, parent: ViewGroup): ViewHolder {
        val viewBinding = ItemNewsBinding.inflate(LayoutInflater.from(context), parent, false)
        return ViewHolder(viewBinding)
    }
}